﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using System.Xml;
using System.IO;
using DE.Sdc.SharePoint.SPContentStructure.Common;

namespace DE.Sdc.SharePoint.SPContentStructure.Import
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = DeploymentConstants.Namespace)]
    [XmlRoot(Namespace = DeploymentConstants.Namespace, IsNullable = false)]
    public class Lists : HierarchicalElement<Web>, IImportDefinition<SPWeb, SPWeb>
    {
        private HierarchicalList<Web, List> _items;

        public Lists()
        {
            Items = new HierarchicalList<Web, List>();
        }

        [XmlElement("List")]
        public HierarchicalList<Web, List> Items
        {
            get { return _items != null ? _items : new HierarchicalList<Web, List>(); }
            set
            {
                _items = value;
                _items.Owner = base.Parent;
            }
        }

        [XmlIgnore]
        public SPWeb UpdatedSPObject { get; internal set; }

        /// <summary>
        /// Updates, replaces or deletes views for a list
        /// </summary>
        /// <param name="web">The parent list where to update, replace or delete the views</param>
        /// <param name="parentWeb"></param>
        public void ImportDefinition(SPWeb web, SPWeb parentWeb)
        {
            // Import Lists
            foreach (List listDefinition in Items)
            {
                SPList list = null;
                DeploymentContext.Current.CurrentObjectType = DeploymentContext.DeploymentObjects.List;
                try
                {
                    listDefinition.Title = DeploymentHelper.Resolve(listDefinition.Title, web.Locale);
                    listDefinition.Url = DeploymentHelper.Resolve(listDefinition.Url, web.Locale);
                    string rootedUrl = DeploymentHelper.GetRootedUrl(listDefinition.Url, web.ServerRelativeUrl);
#if SP_07
                    list = !string.IsNullOrEmpty(rootedUrl)
                                                   ? web.GetList(rootedUrl)
                                                   : web.Lists[listDefinition.Title];
#else
                    list = !string.IsNullOrEmpty(rootedUrl)
                                                   ? web.GetList(rootedUrl)
                                                   : web.Lists.TryGetList(listDefinition.Title);
#endif

                    DeploymentContext.Current.List = list;
                    DeploymentContext.Current.ListDefinition = listDefinition;

                }
                catch (FileNotFoundException ex) { }
                catch (ArgumentNullException ex) { }
                catch (ArgumentException ex) { }

                listDefinition.ImportDefinition(list, web);
            }
            
            UpdatedSPObject = web;
        }
    }
}